package com.plate.auth.config;

import com.plate.auth.expection.OAuthServerAuthenticationEntryPoint;
import com.plate.auth.expection.OAuthServerWebResponseExceptionTranslator;
import com.plate.auth.filter.OAuthServerClientCredentialsTokenEndpointFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

/**
 * @ClassName AuthorizationServerConfig
 * @Description 授权服务器配置类
 * @Author jiaxd
 * @Date 2023年10月22日 11:48
 * @Version 1.0
 */

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private OAuthServerAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * AuthorizationServerConfigurerAdapter需要实现的三个方法如下
     *
     *  public void configure(AuthorizationServerSecurityConfigurer security); 令牌端点安全约束配置
     *  public void configure(ClientDetailsServiceConfigurer clients) throws Exception; 客户端详情配置, 比如秘钥, 唯一Id
     *  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception; 令牌访问端点的配置
     *
     */

    /**
     * 配置客户端详情，并不是所有的客户端都能接入授权服务
     * 在介绍OAuth2.0 协议的时候介绍到，并不是所有的客户端都有权限向认证中心申请令牌的，首先认证
     * 中心要知道你是谁，你有什么资格？
     * 因此一些必要的配置是要认证中心分配给你的，比如客户端唯一Id、秘钥、权限。
     * 客户端配置的存储也支持多种方式，比如内存、数据库
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 先试用内存模式
        clients.inMemory()
                // client_id
                .withClient("jiaxiaodong")
                // client_secret
                .secret(passwordEncoder.encode("123456"))
                //
                .resourceIds("res1")
                // 授权模式，总共四种，1. authorization_code（授权码模式）、password（密码模式）、client_credentials（客户端模式）、implicit（简化模式）
                // refresh_token并不是授权模式
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("all")
                .autoApprove(false)
                .redirectUris("http://www.baidu.com");
    }

    /**
     * 令牌管理服务的配置
     * @return
     */
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        //客户端端配置策略
        services.setClientDetailsService(clientDetailsService);
        //支持令牌的刷新
        services.setSupportRefreshToken(true);
        //令牌服务
        services.setTokenStore(tokenStore);
        //access_token的过期时间
        services.setAccessTokenValiditySeconds(60 * 60 * 2);
        //refresh_token的过期时间
        services.setRefreshTokenValiditySeconds(60 * 60 * 24 * 3);
        // 设置增强令牌, 使用JwtAccessTokenConverter进行转换
        services.setTokenEnhancer(jwtAccessTokenConverter);
        return services;
    }

    /**
     * 令牌访问端点的配置
     * 目前这里仅仅配置了四个，分别如下：
     *                      配置了授权码模式所需要的服务，AuthorizationCodeServices
     *                      配置了密码模式所需要的AuthenticationManager
     *                      配置了令牌管理服务，AuthorizationServerTokenServices
     *                      配置 /oauth/token 申请令牌的uri只允许POST提交。
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .exceptionTranslator(new OAuthServerWebResponseExceptionTranslator())
                .authenticationManager(authenticationManager)
                .tokenServices(tokenServices())
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }


    /**
     * 配置授权服务的安全约束
     * 意味着/oauth/token和/oauth/authorize端点都应该是安全的
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 自定义ClientCredentialsTokenEndpointFilter，用于处理客户端id，密码错误的异常
        OAuthServerClientCredentialsTokenEndpointFilter tokenEndpointFilter = new OAuthServerClientCredentialsTokenEndpointFilter(security, authenticationEntryPoint);
        tokenEndpointFilter.afterPropertiesSet();
        security.addTokenEndpointAuthenticationFilter(tokenEndpointFilter);

        security
                .authenticationEntryPoint(authenticationEntryPoint)
                //开启/oauth/token_key验证端口权限访问
                .tokenKeyAccess("permitAll()")
                //开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess("permitAll()");
                //表示支持 client_id 和 client_secret 做登录认证
//                .allowFormAuthenticationForClients();
    }
}
